import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { getExaminationByUserId,
  getClassesByUserId,
  getStudentScore,
  getExaminationAndStudentScore,
  getKnowledgePointRate,
  getQuestionQuality,
  getAbnormalQuestion
 } from '@/api/server/scoreAnalysisExport';
import { useServerUserStore } from '@/stores/modules/user-server';
import ExcelJS from "exceljs";
import FileSaver from "file-saver";

import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart,BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components'


export const useScoreAnalysisExport = () => {
  use([
    CanvasRenderer,
    LineChart,
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    BarChart
  ])

    const examList = ref([]);
    const userStore = useServerUserStore()
    
    const total = ref(0)
    const page = ref(1)
    const pageSize = ref(10)
    const timeOrder = ref('desc')

    const getExamList = async () => {
        const res = await getExaminationByUserId({
          page: page.value,
          pageSize: pageSize.value,
          timeOrder: timeOrder.value,
          userId: userStore.userInfo.id
        });
        examList.value = res.data.data.list;
        total.value = res.data.data.total;
    };

    const handleReset = () => {
      timeOrder.value = 'desc'
      getExamList()
    }
    
    const handleQuery = async () => {
      await getExamList()
      if(examList.value.length > 0) { 
        ElMessage.success('查询成功') 
      } else {
        ElMessage.warning('暂无数据')
      }
    }


    // 根据用户id和考试id获取班级信息
    const classesInfo = ref([])
    const examinationId = ref(null)
    const getClassesInfo = async () => {
      const res = await getClassesByUserId({
        userId: userStore.userInfo.id,
        examinationId: examinationId.value
      })
      classesInfo.value = res.data.data
    } 

    // 打开导出弹窗
    const exportDialogVisible = ref(false)
    const openExportDialog = async (row) => {
      examinationId.value = row.examinationId
      selectedClasses.value = []
      await getClassesInfo()
      exportDialogVisible.value = true
    }

    // 导出成绩
    const selectedClasses = ref([])
    const selectAllClasses = () => {
      selectedClasses.value = classesInfo.value.map(item => item.classesId)
    }
    const studentScore = ref([])
    const getStudentScoreOfHook = async () => {
      const res = await getStudentScore({
        examinationId: examinationId.value,
        classesIds: selectedClasses.value
      })
      studentScore.value = res.data.data
    }
    // 点击导出按钮，触发执行
    const exportScore = async () => {
      await getStudentScoreOfHook()
      exportExcel(studentScore.value)
    }


      // 导出Excel
    const exportExcel = (dataList) => {
      // 创建工作簿
      const _workbook = new ExcelJS.Workbook();
      // 添加工作表
      const _sheet1 = _workbook.addWorksheet("sheet1");

      _sheet1.columns = [
        { header: "名次", key: "sort", width: 10 },
        { header: "班级", key: "class", width: 20 },
        { header: "姓名", key: "name", width: 20 },
        { header: "得分", key: "score", width: 10 },
      ];

      dataList.forEach(item => {
        _sheet1.addRow({sort: item.sort, class: item.classesName, name: item.studentName, score: item.score});
      });

      const classes = selectedClasses.value.join(',')

      // 导出表格
      _workbook.xlsx.writeBuffer().then((buffer) => {
        let _file = new Blob([buffer], {
          type: "application/octet-stream",
        });
        FileSaver.saveAs(_file, `${dataList[0].examinationName}-${classes}班成绩.xlsx`);
        ElMessage.success('导出成功')
      });
    };

    // 跳转到成绩分析
    const router = useRouter()
    const goToScoreAnalysis = (row) => {
      router.push({
        path: '/score-analysis',
        query: { examinationId: row.examinationId }
      })
    } 

    // 在成绩分析页面中， 返回上一页
    const goBack = () => {
      router.go(-1)
    }

    // 跳转后，获取班级列表
    const examinationIdOfSA = ref(null)
    const classesInfoOfSA = ref([{classesId: 0, classesName: '参与考试的所有班级'}])
    const selectedClassesIdOfSA = ref(0)



    const waitHandleClassesChange = async () => {
      await getExaminationAndStudentScoreOfHook()
    }

    const getClassesInfoOfSA = async () => {
      const res = await getClassesByUserId({
        userId: userStore.userInfo.id,
        examinationId: examinationIdOfSA.value
      })
      if(userStore.userInfo.roleId === 2) {
        classesInfoOfSA.value = [...classesInfoOfSA.value, ...res.data.data]
        selectedClassesIdOfSA.value = classesInfoOfSA.value[0].classesId
      } else if(userStore.userInfo.roleId === 3) {
        classesInfoOfSA.value = res.data.data
        selectedClassesIdOfSA.value = classesInfoOfSA.value[0].classesId
      }
      console.log('跳转后获得的所有班级列表:',classesInfoOfSA.value)
    }

 

    // 获取考试信息和学生成绩
    const examination = ref(null)
    const studentScoreOfSA = ref([])
    const getExaminationAndStudentScoreOfHook = async () => {
      const res = await getExaminationAndStudentScore({
        examinationId: examinationIdOfSA.value,
        classesId: selectedClassesIdOfSA.value
      })
      examination.value = res.data.data.examination
      studentScoreOfSA.value = res.data.data.studentScore
    }

    // 柱状图数据和配置
    const processData = (students) => {

      // 初始化0-100分的计数器
     const scoreDistribution = Array(101).fill(0)
   
     students.forEach(student => {
       // 确保分数在有效范围内
       const score = Math.min(Math.max(Math.floor(student.score), 0), 100)
       scoreDistribution[score]++
     })
   
     // 生成连续的分数数据
     const result = {
       xAxis: [],
       yAxis: []
     }
   
     for (let score = 0; score <= 100; score++) {
       result.xAxis.push(score.toString())
       result.yAxis.push(scoreDistribution[score])
     }
   
     return result
   }
   const chartData = ref(null)
   const option = ref({
    title: {
      text: '分数分布折线图', // 主标题
      left: 'center', // 居中显示
      textStyle: {
        color: '#333',
        fontSize: 16,
        fontWeight: 'bold'
      },
      subtextStyle: {
        color: '#666',
        fontSize: 12
      }
    },
     xAxis: {
       type: 'category',
       data: chartData.xAxis,
       name: '分数', // 设置X轴标题
       nameLocation: 'end', // 标题位置（'start' | 'center' | 'end'）
     },
     yAxis: { type: 'value',name: '人数',nameLocation: 'end',interval: 1, },
     series: [{
       type: 'line',
       data: chartData.yAxis,
       connectNulls: true, // 跳过空值连接
       smooth: 1,
       symbol: 'none',
       lineStyle: { width: 1 },
       areaStyle: { color: 'rgba(24, 144, 255, 0.1)' },
       sampling: 'lttb',
     }],
    
   });
   

    // 柱状图变化
    const handleChartChange = async () => {
      chartData.value = processData(studentScoreOfSA.value)
      option.value.xAxis.data = chartData.value.xAxis
      option.value.series[0].data = chartData.value.yAxis
    }

    
    // 获得知识点得分率数据
    const kpData = ref([])
    const optionOfKp = ref(null)
    const getKpDataOfHook = async () => {
      const res = await  getKnowledgePointRate({
        examinationId: examinationIdOfSA.value,
        classesId: selectedClassesIdOfSA.value
      })
      kpData.value = res.data.data
      optionOfKp.value = {
        title: {
          text: '知识点掌握情况分析',
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const data = kpData.value[params[0].dataIndex];
            return `
              <div style="font-weight:bold">${data.knowledgePointName}</div>
              <div>平均分：<span style="color:#1890ff">${data.averageScore}</span></div>
              <div>最高分：<span style="color:#13c2c2">${data.maxScore}</span></div>
              <div>得分率：<span style="color:${data.scoreRate > 0.7 ? '#52c41a' : '#f5222d'}">
                ${(data.scoreRate * 100).toFixed(0)}%
              </span></div>
            `;
          }
        },
        legend: {
          data: ['得分率', '平均分', '最高分'],
          top: 50,
          itemWidth: 20,
          itemHeight: 12
        },
        grid: {
          top: 100,
          left: 50,
          right: 50,
          bottom: 30,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: kpData.value.map(item => item.knowledgePointName),
          axisLabel: {
            interval: 0,
            rotate: 30,
            fontSize: 12
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '分数',
            min: 0,
            max: 100,
            interval: 20,
            axisLine: {
              show: true
            },
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '得分率',
            min: 0,
            max: 1,
            interval: 0.2,
            axisLine: {
              show: true
            },
            axisLabel: {
              formatter: (val) => `${(val * 100).toFixed(0)}%`
            }
          }
        ],
        series: [
          {
            name: '得分率',
            type: 'bar',
            barWidth: 20,
            data: kpData.value.map(item => item.scoreRate ),
            yAxisIndex: 1,
            itemStyle: {
              color: (params) => {
                return params.value > 0.7 ? '#52c41a' : '#f5222d';
              }
            },
            label: {
              show: true,
              position: 'top',
              formatter: (params) => `${(params.value * 100).toFixed(0)}%`
            }
          },
          {
            name: '平均分',
            type: 'line',
            data: kpData.value.map(item => item.averageScore),
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: '#1890ff'
            },
            itemStyle: {
              color: '#1890ff'
            },
            label: {
              show: true,
              position: 'top',
              formatter: '{c}'
            }
          },
          {
            name: '最高分',
            type: 'line',
            data: kpData.value.map(item => item.maxScore),
            symbol: 'diamond',
            symbolSize: 10,
            lineStyle: {
              width: 2,
              type: 'dashed',
              color: '#13c2c2'
            },
            itemStyle: {
              color: '#13c2c2'
            }
          }
        ]
      }
      console.log('知识点得分率数据:',kpData.value)
    } 

    // 获得试题质量分析数据
    const questionQualityData = ref([])
    const getQuestionQualityOfHook = async () => {
      const res = await getQuestionQuality({
        examinationId: examinationIdOfSA.value,
        classesId: selectedClassesIdOfSA.value
      })
      questionQualityData.value = res.data.data
     
      }

    // 获得异常试题信息
    const abnormalQuestionData = ref([])
    const examinationOfAbnormalQuestion = ref(null)
    const getAbnormalQuestionOfHook = async () => {
      const res = await getAbnormalQuestion({
        examinationId: examinationIdOfSA.value,
        classesId: selectedClassesIdOfSA.value
      })  
      abnormalQuestionData.value = res.data.data.abnormalQuestions
      examinationOfAbnormalQuestion.value = res.data.data.examination
    } 

    // 点击导出异常试题按钮，触发执行
    const exportAbnormalQuestion = async () => {
      await getAbnormalQuestionOfHook()
      if(abnormalQuestionData.value.length > 0) {
      exportExcelOfAbnormalQuestion(abnormalQuestionData.value)
      } else {
        ElMessage.warning('暂无数据')
      }
    }

    const exportExcelOfAbnormalQuestion = (dataList) => {
      // 创建工作簿
      const _workbook = new ExcelJS.Workbook();
      // 添加工作表
      const _sheet1 = _workbook.addWorksheet("sheet1");

      _sheet1.columns = [
        { header: "试题名称", key: "questionName", width: 100 },
        { header: "所属大题", key: "bigQuestionName", width: 20 },
        { header: "难度系数", key: "difficultyCoefficient", width: 20 },
        { header: "难度评级", key: "qualityLevel", width: 10 },
        { header: "改进建议", key: "suggestion", width: 10 },
      ];

      dataList.forEach(item => {
        _sheet1.addRow({questionName: item.questionName, bigQuestionName: item.bigQuestionName, difficultyCoefficient: item.difficultyCoefficient, qualityLevel: item.qualityLevel, suggestion: item.suggestion});
      });

      const fileName = `${examinationOfAbnormalQuestion.value.examinationName} / ${examinationOfAbnormalQuestion.value.startTime} - ${examinationOfAbnormalQuestion.value.endTime} / ${selectedClassesIdOfSA.value}班异常题目.xlsx`

      // 导出表格
      _workbook.xlsx.writeBuffer().then((buffer) => {
        let _file = new Blob([buffer], {
          type: "application/octet-stream",
        });
        FileSaver.saveAs(_file, fileName);
        ElMessage.success('导出成功')
      });
      
    }


    const waitAllApi = async () => {
      await getClassesInfoOfSA()
      await getExaminationAndStudentScoreOfHook()
      await handleChartChange()
      await getKpDataOfHook()
      await getQuestionQualityOfHook()
    }

       // 选择班级
       const handleClassesChange = async () => {
        console.log('examinationIdOfSA:',examinationIdOfSA.value)
        console.log('selectedClassesIdOfSA:',selectedClassesIdOfSA.value)
        await waitHandleClassesChange()
        await handleChartChange()
        await getKpDataOfHook()
        await getQuestionQualityOfHook()
      }

    return { 
      examList,
      total,  
      page,
      pageSize,
      timeOrder,
      getExamList,
      handleReset,
      handleQuery,

      // 班级信息
      classesInfo,
      examinationId,
      getClassesInfo,

      // 导出弹窗
      openExportDialog,
      exportDialogVisible,

      // 导出成绩
      selectedClasses,
      selectAllClasses,
      exportScore,

      // 跳转到成绩分析
      goToScoreAnalysis,

      // 返回上一页
      goBack,
      // 跳转后，用于接收 考试id
      examinationIdOfSA,
      // 选择班级
      selectedClassesIdOfSA,


      waitAllApi,
      classesInfoOfSA,

      // 选择班级
      handleClassesChange,

      // 获取考试信息和学生成绩
      examination,
      studentScoreOfSA,

      // 柱状图
      chartData,
      option,
      handleChartChange,

      // 知识点得分率数据
      kpData,
      optionOfKp,
     
      // 试题质量分析数据
      questionQualityData,

      // 异常试题信息
      exportAbnormalQuestion
    
    };
};  
